package net.cl.utils;

import java.io.UnsupportedEncodingException;

/**
 * 字节工具类
 * 
 * @author CaoLei
 */
public class ByteUtil {

	public final static byte[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

	/**
	 * 切换字节顺序<br>
	 * jdk 1.5以后可以用<code>Integer.reverseBytes(int i)</code>
	 */
	public final static int swabInt(int i) {
		return (i >>> 24) | (i << 24) | ((i << 8) & 0x00FF0000) | ((i >> 8) & 0x0000FF00);
	}

	/**
	 * 二进制数组转十六进制字符串
	 */
	public static String bytes2HexString(byte[] bytes) {
		if (bytes == null)
			return null;
		try {
			byte[] hex = new byte[2 * bytes.length];
			int index = 0;
			for (int i = 0; i < bytes.length; i++) {
				int v = bytes[i] & 0xFF; // 将8位的byte转为32位的int时,java会自动补位,若是正数,会补24位0,若是负数,会补24位1,用0xFF与可以把高24位清0
				hex[index++] = HEX[v >>> 4]; // 一个byte的前四位
				hex[index++] = HEX[v & 0xF]; // 一个byte的后四位
			}
			return new String(hex, "ASCII");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
	}

	/**
	 * 十六进制字符串转二进制数组
	 */
	public static byte[] hexString2Bytes(String hex) {
		if (hex == null)
			return null;
		char[] c = hex.toCharArray();
		int length = c.length / 2;
		byte[] b = new byte[length];
		int index = 0;
		for (int i = 0; i < length; i++) {
			int high = Character.digit(c[index++], 16);
			int low = Character.digit(c[index++], 16);
			int v = (high << 4) | low;
			if (v > 127)
				v -= 256;
			b[i] = (byte) v;
		}
		return b;
	}

	public static String unicode2String(byte[] bytes) {
		if (bytes == null)
			return "";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length;) {
			int low = bytes[i++];
			int high = bytes[i++];
			char b = (char) ((low & 0xff) | ((high << 8) & 0xff00));
			sb.append(b);
		}
		return sb.toString();
	}

}
